define(['common/js/service/menu-request-service-0.1',
	'common/js/service/boss-storage-service-0.1'],
function() {
	controllerModule.controller("MenuController", function ($rootScope, $scope, $location, $injector,$timeout, dataStorage,asyncDataStorage, MaiDialog, UserService, $window) {
		$scope.menus = [];
		$scope.selectedMenus = [];
		$scope.selectedIndexes = [0];

		//获取菜单列表
		//获取菜单列表
		$scope.loadMenus = function (serviceName, serviceMethod,initUrl) {
			var menusPath = window.location.pathname;
			var menuData = dataStorage.getItem(menusPath);
			if (menuData == null || menuData.length == 0) {
				var DataService = $injector.get(serviceName);
				//根据最新的条件获取数据
				var promise = DataService[serviceMethod]();
				promise.then(function (data) {
					if(data == null||data.length == 0){
						MaiDialog.alert("权限不足，请联系管理员",function(){
							UserService.logout().then(function (data) {
								//清除session
								dataStorage.clearItem("currentUser");
								dataStorage.clearItem(menusPath);

								window.location.href = rootPath + "/view/main/login#/";
							});
						});
					}else{
						menuData = data;
						dataStorage.saveItem(menusPath, menuData);
						$scope.menus = menuData;
					}
				});
			}
			if (menuData != null) {
				$scope.menus = menuData;
			}
		};
		$scope.pathTo = pathTo;
		//监听菜单展开广播请求
		$scope.$on("expand-menu-tree",function(event,url,params){
			var indexStr = retriveIndexStrByUrl($scope.menus,url);
			pathTo(indexStr,1,params);
		});

		function pathTo(indexStr, leaf,params) {
			//如果有就删除
			$('body').removeClass('modal-open');

			//如果不是叶子菜单，不处理
			if (!leaf || leaf != 1) {
				return;
			}

			$scope.activeIndex = indexStr;

			var indexes = indexStr.split("_");
			$scope.selectedIndexes = indexes;


			var tmpMenu = $scope.menus[indexes[0]];
			var newSArr = new Array();
			newSArr.push(tmpMenu);

			for (var i = 1; i < indexes.length; i++) {
				tmpMenu = tmpMenu.children[indexes[i]];
				newSArr.push(tmpMenu);
			}

			$scope.selectedMenus = newSArr;

			//设置标题
			var deepMenu = $scope.selectedMenus[$scope.selectedMenus.length - 1];
			$rootScope.title = deepMenu.menuName;

			var routeParams = {};
			if(params){
				routeParams = params;
			}
			$location.path(deepMenu.url).search(routeParams);
		}

		function retriveInitialIndexStr(menus) {
			if (!menus || menus.length <= 0) {
				return "";
			}

			var retStr = retriveInitialIndexStr(menus[0].children);
			return "0" + (retStr ? "_" + retStr : "");
		}

		function retriveIndexStrByUrl(menus,url){
			if (!menus || menus.length <= 0) {
				return "";
			}

			for(var index in menus){
				if(menus[index].leaf == 1 && menus[index].url == url){
					return index;
				}

				var retStr = retriveIndexStrByUrl(menus[index].children,url);

				if(retStr) {
					return index + '_' + retStr;
				}
			}
		}

	});
});